package dmp.cjh.url.domain;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;

public class URLUtils {

	public static String regexpExtract(String str, String regex) {
		if (str == null || regex == null) {
			return "";
		}
		Pattern REGEX_PATTERN = Pattern.compile(regex);
		Matcher matcher = REGEX_PATTERN.matcher(str);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";
	}
	
	public static Map<String, String> getQueryMap(String str) {
		Map<String, String> map = new HashMap<String, String>();
		if (str == null) {
			return map;
		}
		String[] querys = str.split("&");
		for (String query : querys) {
			int pos = query.indexOf("=");
			if (pos != -1 && pos != 0 && pos != query.length()) {
				map.put(query.substring(0, pos), query.substring(pos+1, query.length()));
			}
		}
		return map;
	}
	
	public static String removePunctuations(String str) {
		if (str == null) {
			return "";
		}
		return str.replaceAll("[\\pP\\pZ\\pS]", "");
	}
	
	
	public static String getValueByParam(String url,Map<String, String> params){
		String re="";
		Set<String> keys = params.keySet();
		for (String key : keys) {
			if(url.contains(key)){
				re=get_each_value(params.get(key),url);
			}
		}
		return re;
	}
	
	
	private static List<String> full_regexpExtract(String url, String regex) {
		if (url == null || regex == null) {
			return null;
		}
		String domain = regex.substring(0, regex.indexOf("/"));
		
		List<String> re = new ArrayList();
		
		re.add(domain);

		Pattern REGEX_PATTERN = Pattern.compile(regex);
		Matcher matcher = REGEX_PATTERN.matcher(url);
		if (matcher.find()) {
			
			for (int i = 1; i <= matcher.groupCount(); i++) {
				
				re.add(matcher.group(i));
			}

		}
		return re;
	}
	
	
	
	
	
	
	
	private static String get_each_value(String param, String url) {
		
		URL urlParser = null;
		try {
			urlParser = new URL(url);
		} catch (MalformedURLException e) {

		}
		
		Map<String, String> map = URLUtils.getQueryMap(urlParser.getQuery());
		String[] strs = param.split("\\|");
		
		List<String> list = new ArrayList<>();
		String result;

		if (strs.length >1) {
			String domain = strs[0];
			list.add(domain);

			for (int i = 1; i < strs.length; i++) {
				if (map.containsKey(strs[i])) {
					list.add(map.get(strs[i]));
				}
			}
			result = ArrayUtils.toString(list);
//			System.out.println(result);
		} else {
			
			String regex = param.replaceAll("\\$\\{[^}]*}", "([[^)]*]*)");

			String domain = param.substring(0, param.indexOf("/"));
			
			list = full_regexpExtract(url, regex);
		
			result = ArrayUtils.toString(list);
			
//			System.out.println(result);
		}
		
		return result;

	}
	
	
}
